﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

public class CsRedisHelper : RedisHelper<CsRedisHelper>
{
    static DateTime _dt1970 = new DateTime(1970, 1, 1);

    /// <summary>
    /// 此方法redis操作不使用异步,只在获取数据异步
    /// </summary>
    async public static Task<T> CacheShellzAsync<T>(string key, int timeoutSeconds, Func<Task<T>> getDataAsync)
    {
        if (timeoutSeconds == 0) return await getDataAsync();
        T cacheValue;
        try
        {
            cacheValue = Get<T>(key);
        }
        catch (Exception)
        {
            Del(key);
            throw;
        }
        if (cacheValue != null)
        {
            return cacheValue;
        }
        else
        {
            var ret = await getDataAsync();
            Set(key, ret, timeoutSeconds);
            return ret;
        }
    }

    /// <summary>
    /// 此方法redis操作不使用异步,只在获取数据异步
    /// </summary>
    async public static Task<T> CacheShellzAsync<T>(string key, string field, int timeoutSeconds, Func<Task<T>> getDataAsync)
    {
        if (timeoutSeconds == 0) return await getDataAsync();
        try
        {
            var value = HGet<(T, long)>(key, field);
            if (DateTime.Now.Subtract(_dt1970.AddSeconds(value.Item2)).TotalSeconds <= timeoutSeconds) return value.Item1;
        }
        catch (Exception)
        {
            HDel(key, field);
            throw;
        }

        var ret = await getDataAsync();
        HSet(key, field, (ret, (long)DateTime.Now.Subtract(_dt1970).TotalSeconds));
        return ret;
    }
}
